<template>
  <div class="mark-content-header">
    <span class="title">打分板</span>
    <slot name="titleButton"></slot>
  </div>
  <div class="mark_info">
    <div class="score-main">
      <div class="topics-container" @click.self="selfFunClick">
        <div class="topic-item">
          <div class="topic-item-title">{{ currentTopic.tmbh }}</div>
          <InputNumber
            ref="input"
            style="width: 100%"
            :value="currentTopic.score"
            :min="0"
            :controls="false"
            :placeholder="`满分${currentTopic.tmfz ?? '--'}分`"
            :max="currentTopic.tmfz"
            @change="handleChange"
          />
        </div>
        <a-row justify="center" @click.self="selfFunClick">
          <template v-if="!Data.isShowCount">
            <template v-for="(item, index) in countList" :key="index">
              <a-button class="count" @click="handleClick(index)">
                {{ `${item[0]} - ${item[item.length - 1]}` }}
              </a-button>
            </template>
          </template>
          <template v-else>
            <template v-for="(item, index) in countList[countIndex]" :key="index">
              <a-button
                class="count"
                @click="markClick(item)"
                draggable="true"
                @dragstart="dragstart($event, item)"
              >
                {{ item }}
              </a-button>
            </template>
            <div class="w-full text-center pt-2 text-[#777]" @click.self="selfFunClick">
              温馨提示：点击空白还原分数区间
            </div>
          </template>
        </a-row>
      </div>
      <div class="topics-container scorePoint" v-if="currentTopic.dfdInfoList?.length">
        <div class="scoreTitle">得分点</div>
        <div class="scoreLis">
          <a-radio-group @change="stLxSeleFun" v-model:value="dfdSelected" button-style="solid">
            <span
              v-for="(item, index) in currentTopic.dfdInfoList"
              class="inline-block itemRoade mr-1 mb-1 rounded-md p-1"
              :class="tagsList.find(ele => ele.pyDfdId == item.pyDfdId) ? 'bg-[#0f0]' : ''"
              :title="`${item.sortNum}:${item.contents}(${item.dfdScore}分)`"
            >
              <a-radio :value="item.pyDfdId" :key="item.pyDfdId">
                {{ index + 1 }}({{ item.dfdScore }}分):{{ item.contents }}
              </a-radio>
            </span>
          </a-radio-group>
          <div class="w-full text-center pt-2 text-[#777]"> 温馨提示：绿色表示已评分 </div>
        </div>
      </div>
      <div class="h-l tips">
        <span class="line"></span>
        <span class="label">试题得分：</span>
        <span class="value">{{ currentTopic.score ?? '--' }}分</span>
        <span class="line"></span>
      </div>
      <a-form ref="setForm" :model="form">
        <div
          v-if="
            currentTopic.score === 0 &&
            ((!!currentTopic?.dfdInfoList?.length &&
              currentTopic?.dfdInfoList?.length == tagsList?.length) ||
              !currentTopic?.dfdInfoList?.length)
          "
        >
          <a-form-item
            label="零分原因"
            :rules="{
              required: currentTopic.tmlx != '判断题' && currentTopic.tmlx != '填空题',
              message: '请选择零分原因',
              trigger: 'change',
            }"
            name="lfCode"
          >
            <a-radio-group size="small" v-model:value="form.lfCode" button-style="solid">
              <div v-for="item in lfYcList" :key="item.value">
                <a-radio :value="item.value">
                  {{ item.label }}
                </a-radio>
              </div>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            label="零分备注"
            name="lfBz"
            :rules="{
              required: form.lfCode === 'qt',
              message: '请输入零分备注',
              trigger: 'blur',
            }"
          >
            <a-textarea v-model:value="form.lfBz" placeholder="请输入零分备注" />
          </a-form-item>
        </div>
        <a-form-item label="评分备注" name="pyBz">
          <a-textarea v-model:value="form.pyBz" placeholder="请输入评分备注" />
        </a-form-item>
      </a-form>
      <a-button
        type="primary"
        :disabled="isSubmitDisabled"
        :loading="pageLoading"
        class="submit truncate"
        @click="handleSubmit(false)"
        :title="submitTip"
      >
        {{ submitTip || '提交并评阅下一题' }}
      </a-button>
      <a-button
        type="primary"
        :disabled="isSubmitDisabled"
        :loading="pageLoading"
        class="submit truncate"
        @click="handleSubmit(true)"
        :title="submitTip"
      >
        {{ submitTip || '提交并退出阅卷' }}
      </a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, reactive, h, nextTick } from 'vue'
import { InputNumber } from 'ant-design-vue'
import { throttle } from 'lodash-es'
import { useRouter } from 'vue-router'
import { useTeacherMarkStore } from '/@/store/modules/teacherMark'
import { useMessage } from '/@/hooks/web/useMessage'
import { useUserStore } from '/@/store/modules/user'
import { submitTopic, todoYcDftTopic } from '/@/api/teacher'
import dayjs from 'dayjs'
const { createMessage, createConfirm } = useMessage()
const userStore = useUserStore()

const startTime: any = computed(() => userStore.getStartTime)

const router = useRouter()

const teacherMarkStore = useTeacherMarkStore()

//   选中得分点
const dfdSelected: any = ref('')
const stLxSeleFun = e => {
  currentTopic.value.dfdInfoList.forEach((ele, index) => {
    if (e.target.value == ele.pyDfdId) {
      currentTopic.value.tmfz = ele.dfdScore
      teacherMarkStore.setDfdSelected({ ...ele, index: index + 1 })
    }
  })
}

const addSubjectForm = computed(() => userStore.getSysConfig)

let pyTpZs = 0

// 是否校验图片全部点击查看
const isCheckImg = computed(() => {
  let imgLength = currentTopic.value?.dtkqtxxVoList?.length
  let clickTimes = 0
  pyTpZs = 0
  currentTopic.value?.dtkqtxxVoList?.forEach(ele => {
    if (ele.clickTimes) clickTimes += 1
    pyTpZs += ele.clickTimes || 0
  })
  return imgLength != clickTimes
})

const form: any = ref({})

const setForm = ref()

const questionsInfo = computed(() => teacherMarkStore.getQuestions)
const pageLoading = computed(() => teacherMarkStore.getLoading)

const Data = reactive({
  isShowCount: false,
} as any)

function selfFunClick() {
  Data.isShowCount = false
}

// 当前题目评阅标准
const currentTopic = computed(() => teacherMarkStore.getCurrentTopic ?? {})
// 渲染打分项
const countList: any = ref([])
const renderMarkCount = (max, step) => {
  countList.value = []
  selfFunClick()
  // 所有打分项
  const stepCountList = Array.from(new Array(max / step), (_x, i) => (i + 1) * step)
  // 最大行数
  const rowCount = Math.ceil(stepCountList.length / 10)
  for (let i = 0; i < rowCount; i++) {
    countList.value.push(stepCountList.slice(i * 10, (i + 1) * 10))
  }
  countList.value[0].unshift(0)
  teacherMarkStore.setCountList(countList.value)
}

const props = defineProps({
  lfYcList: {
    type: Array,
    default: () => [],
  },
  disabledSubmitButton: {
    type: Boolean,
    default: false,
  },
} as any)

watch(
  [() => currentTopic.value.tmfz, () => currentTopic.value.pydfgc],
  ([val, val2]) => {
    if (val && val2)
      renderMarkCount(Number(currentTopic.value.tmfz), Number(currentTopic.value.pydfgc))
  },
  { immediate: true }
)

const tagsList = computed(() => teacherMarkStore.getTagsList)

const countIndex = ref(0)
const handleClick = i => {
  countIndex.value = i
  Data.isShowCount = true
}

// 打分
const markClick = value => {
  createMessage.warning('请拖拽评分')
}

const handleChange = val => {
  if (val == null) {
    // currentTopic.value.score = null
  }
}

// 拖拽打分
const dragstart = (e, value) => {
  if (value > currentTopic.value.tmfz) {
    return createMessage.error('非法分数')
  }
  const data = JSON.stringify({ value })
  e.dataTransfer.setData('data', data)
}

/**
 * 禁止提交按钮
 */

/**
 * 提交禁用状态
 */
let isSubmitDisabled = computed(
  () =>
    !!(
      props.disabledSubmitButton ||
      !currentTopic.value?.dtkqtxxVoList?.length ||
      typeof currentTopic.value?.score !== 'number' ||
      !tagsList.value?.length ||
      (!!currentTopic.value?.dfdInfoList?.length &&
        currentTopic.value?.dfdInfoList?.length > tagsList.value?.length) ||
      +new Date() - +new Date(startTime.value) < addSubjectForm.value?.pyLoadingSeconds ||
      (addSubjectForm.value?.clickDtkqtCheck4ZgtFlag &&
        isCheckImg.value &&
        !questionsInfo.value?.pyZycIdList) ||
      (currentTopic.value?.score === 0 &&
        (!form.value.lfCode || (form.value.lfCode === 'qt' && !form.value.lfBz)))
    )
)

/**
 * 提交按钮提示信息

 */
let submitTip = computed(() => {
  let test = ''

  

  if (
    addSubjectForm.value.clickDtkqtCheck4ZgtFlag &&
    isCheckImg.value &&
    !questionsInfo.value.pyZycIdList //表示重评题
  )
    test = '请查看全部图片'

  // let durationNum = (+new Date() - +new Date(startTime.value)) / 1000 //当前试题评阅时长
  // if (durationNum < addSubjectForm.value.pyLoadingSeconds) {
  //   test = `请你在${Math.ceil(addSubjectForm.value.pyLoadingSeconds - durationNum)}秒后提交`
  // }

  if (
    currentTopic.value?.score === 0 &&
    (!form.value.lfCode || (form.value.lfCode === 'qt' && !form.value.lfBz))
  ) {
    test = '请设置零分原因'
  }

  if (
    !!currentTopic.value?.dfdInfoList?.length &&
    currentTopic.value?.dfdInfoList?.length > tagsList.value?.length
  ) {
    test = '请对所有得分点进行评分'
  }

  if (typeof currentTopic.value?.score !== 'number' || !tagsList.value?.length) {
    test = '请进行评阅'
  }

  if (!currentTopic.value?.dtkqtxxVoList?.length) {
    test = '获取试卷失败'
  }

  return test
})

// 提交试卷
const handleSubmit = throttle(
  async (isDropOut = false) => {
    await setForm.value?.validate()
    if (!currentTopic.value.dtkqtxxVoList.length)
      return createMessage.error('当前试卷没有获取到图片,不能进行评阅提交')

    let sumAlue = 0
    if (currentTopic.value.dfdInfoList?.length) {
      currentTopic.value.dfdInfoList.forEach(ele => {
        sumAlue += Number(ele.dfdScore)
      })
    } else {
      sumAlue = currentTopic.value.tmfz
    }

    if (typeof currentTopic.value?.score !== 'number' || !tagsList.value.length) {
      return createMessage.error('您还未对试题进行评分')
    } else if (currentTopic.value?.score > sumAlue) {
      return createMessage.error('您评阅的分数是非法分数')
    }

    let durationNum = (+new Date() - +new Date(startTime.value)) / 1000 //当前试题评阅时长
    if (durationNum < addSubjectForm.value.pyLoadingSeconds) {
      createMessage.error(
        `请你在${Math.ceil(addSubjectForm.value.pyLoadingSeconds - durationNum)}秒后提交评阅结果`
      )
      return
    }

    if (
      addSubjectForm.value.clickDtkqtCheck4ZgtFlag &&
      isCheckImg.value &&
      !questionsInfo.value.pyZycIdList //表示重评题
    ) {
      createConfirm({
        iconType: 'error',
        title: () => h('span', '温馨提醒'),
        content: () => h('span', '请点击查看所有图片后再提交'),
        onOk: async () => {},
      })
      return
    }

    if (
      !!currentTopic.value?.dfdInfoList?.length &&
      currentTopic.value?.dfdInfoList?.length > tagsList.value?.length
    ) {
      return createMessage.error('请对所有得分点进行评分')
    }

    try {
      if (pageLoading.value) return //防止多次提交
      teacherMarkStore.setLoading(true)
      const params: any = {
        pyTpZs,
        pyZdf: currentTopic.value.score,
        pyKssj: startTime.value, // 开始打分时间
        pyTjsj: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 提交时间
        pyZycId: questionsInfo.value.pyZycId || questionsInfo.value.pyZycIdList[0], // 资源池id
        fpFlag: questionsInfo.value.fpFlag, //是否为复评题
        lfCode: currentTopic.value.score === 0 ? form.value?.lfCode : undefined,
        lfBz: currentTopic.value.score === 0 ? form.value?.lfBz : undefined,
        pyBz: form.value?.pyBz,
      }

      let dfdSubmitList: any = []

      if (tagsList.value.length == 1 && tagsList.value[0]?.pyDfdId == 'totleScole') {
        params.pyDtkqtId = tagsList.value[0].pyDtkqtId
        params.pyLocation = `${tagsList.value[0].x},${tagsList.value[0].y}`
      } else {
        tagsList.value.forEach((ele: any) => {
          dfdSubmitList.push({
            pyDtkqtId: ele.pyDtkqtId,
            pyLocation: `${ele.x},${ele.y}`,
            pyScore: ele.value,
            pyDfdId: ele.pyDfdId,
            dfdId: ele.dfdId,
            pyDfdAutoId: ele.pyDfdAutoId,
          })
        })
        params.dfdSubmitList = dfdSubmitList
      }

      let res: any = {}
      if (!questionsInfo.value.pyZycId) {
        //重评题
        res = await todoYcDftTopic(params)
      } else {
        res = await submitTopic(params)
      }

      if (res.code === 200) {
        form.value = {}
        createMessage.success('提交成功！')
        // 是否退出阅卷
        if (isDropOut) {
          router.back()
          return
        }
        // 获取下一次试题试卷标识符
        teacherMarkStore.setNext(true)
      } else if (res.code === 8200) {
        router.back()
        createMessage.warning(res.message)
      } else {
        createMessage.error(res.message)
      }
    } catch (error) {
      createMessage.error('提交失败，请稍后重试！')
    } finally {
      teacherMarkStore.setLoading(false)
    }
  },
  1000,
  {
    trailing: false,
  }
)

watch(
  () => [tagsList.value, currentTopic.value.dfdInfoList],
  () => {
    let dfdInfoList = currentTopic.value.dfdInfoList
    let numIndex = tagsList.value?.length
    if (dfdInfoList?.length && numIndex < dfdInfoList.length) {
      if (numIndex !== 0) {
        for (let i = 0; i < dfdInfoList.length; i++) {
          if (!tagsList.value.find(item => item.pyDfdId === dfdInfoList[i].pyDfdId)) {
            numIndex = i
            break
          }
        }
      }
      teacherMarkStore.setDfdSelected({
        ...dfdInfoList[numIndex],
        index: numIndex + 1,
      })
      currentTopic.value.tmfz = dfdInfoList[numIndex].dfdScore
      dfdSelected.value = dfdInfoList[numIndex].pyDfdId
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

function outUpSubmit(val: any = {}, isDropOut = false) {
  form.value = val
  if (isDropOut) {
    nextTick(() => {
      setForm.value?.validate()
      handleSubmit(false)
    })
  }
}

defineExpose({
  outUpSubmit,
})
</script>
<style lang="less" scoped>
.mark-content-header {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 2px solid #ddd;
  justify-content: space-between;
  .title {
    font-size: 16px;
    font-weight: 700;
    margin-right: 20px;
    color: #3e98e8;
  }
}
.mark_info {
  overflow-y: auto;
  height: calc(100% - 50px);

  .score-main {
    padding: 20px;
    width: 100%;

    .topics-container {
      width: 100%;
      height: 220px;
      overflow-y: auto;
      .topic-item,
      .child-item {
        display: flex;
        flex-direction: column;
      }

      .topic-item-title {
        font-size: 20px;
        font-weight: 600;
      }
      .count {
        margin: 5px;
        font-weight: 700;
      }

      .topic-child-content {
        padding-left: 30px;
      }
    }

    .scorePoint {
      display: flex;
      flex-direction: column;
      overflow-x: hidden;
      box-sizing: border-box;
      .scoreTitle {
        font-size: 15px;
        padding: 5px 0;
        font-weight: 600;
      }

      .scoreLis {
        flex: 1;
        overflow-y: auto;
      }
      .itemRoade {
        ::v-deep(.ant-radio-wrapper) {
          max-width: 150px;
          margin: 0;
          span:last-child {
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
        }
      }
    }

    .tips {
      margin-top: 30px;
      display: flex;
      align-items: center;
      justify-content: center;

      .label {
        font-size: 16px;
        font-weight: bold;
        color: #e52a2a;
        margin-left: 10px;
      }

      .value {
        font-size: 24px;
        font-weight: bold;
        color: #e52a2a;
        margin-right: 10px;
      }

      .line {
        width: 54px;
        opacity: 0.28;
        border: 1px solid rgba(63, 67, 85, 0.5);
      }
    }

    .stleinput {
      padding: 0 10px 5px;
      label {
        font-size: 15px;
        font-weight: 600;
      }
    }

    .submit {
      margin: 10px auto;
      padding: 10px 0;
      width: 100%;
      height: auto;
    }
  }
}
</style>
